package common.liusany.admin.web.admin;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import common.liusany.admin.entity.account.User;
import common.liusany.admin.service.account.AccountManager;

/**
 * 使用@ModelAttribute, 实现Struts2 Preparable二次绑定的效果。 因为@ModelAttribute被默认执行,
 * 而其他的action url中并没有${id}，所以需要独立出一个Controller.
 * 
 * @author calvin
 */
@Controller
@RequestMapping(value = "/admin/user/")
public class UserDetailController extends BaseCopntroller{

	private AccountManager accountManager;

	private GroupListEditor groupListEditor;

	@InitBinder
	public void initBinder(WebDataBinder b) {
		b.registerCustomEditor(List.class, "groupList", groupListEditor);
	}

	@RequestMapping(value = "update/{id}", method = RequestMethod.GET)
	public String updateForm(Model model) {
		model.addAttribute("allGroups", accountManager.getAllGroup());
		return "admin/adminForm";
	}

	@RequestMapping(value = "save/{id}", method = RequestMethod.POST)
	public String save(@ModelAttribute("user") User user,
			RedirectAttributes redirectAttributes,Model model) {
		accountManager.saveUser(user);
		redirectUrl = "admin/user/list";
		model.addAttribute("message", "修改用户" + user.getName() + "成功");
		model.addAttribute("redirectUrl", redirectUrl);
		
		return SUCCESS;
	}

	@ModelAttribute("user")
	public User getAccount(@PathVariable("id") Long id) {
		return accountManager.getUser(id);
	}

	@Autowired
	public void setAccountManager(AccountManager accountManager) {
		this.accountManager = accountManager;
	}

	@Autowired
	public void setGroupListEditor(GroupListEditor groupListEditor) {
		this.groupListEditor = groupListEditor;
	}

}
